package cn.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Code56 {

    public static void main(String[] args) {
        int[][] intervals = {{3,3},{2,6},{8,10},{15,18},{16,17}};
        int[][] merge = fun(intervals);
        System.out.println();
    }

    public static int[][] fun(int[][] intervals) {
        Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
        List<int[]> result = new ArrayList<>();
        for(int i=0; i< intervals.length; i++){
            if(i == 0){
                result.add(new int[]{intervals[i][0],intervals[i][1]});
            } else {
                int ii = result.size() - 1;
                int[] array = result.remove(ii);
                if(array[0] <= intervals[i][0] && array[1] >= intervals[i][0]){
                    result.add(new int[]{array[0], Math.max(array[1], intervals[i][1])});
                }else {
                    result.add(array);
                    result.add(new int[]{intervals[i][0],intervals[i][1]});
                }
            }
        }
        int[][] arr = new int[result.size()][2];
        for (int i = 0; i < result.size(); i++) {
            arr[i][0] = result.get(i)[0];
            arr[i][1] = result.get(i)[1];
        }
        return arr;
    }
}
